package com.ljx.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljx.entity.MyUser;
import com.ljx.entity.Permission;
import com.ljx.mapper.PermissionMapper;
import com.ljx.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2023/1/3 15:21
 * @Version 1.0
 */
@Service
public class UserService implements UserDetailsService {
	@Resource
	private UserMapper userMapper;

	@Resource
	private PermissionMapper permissionMapper;

	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		// 根据账户查询用户信息
		QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
		wrapper.eq("username",s);
		MyUser myUser = userMapper.selectOne(wrapper);

		if(myUser!=null){
			// 2查询该用户具有的权限
			List<Permission> permissions = permissionMapper.findPermissionByUserId(myUser.getUserid());
			/*
			* loadUserByUsername他返回的是一个UserDetails接口，我们需要返回他的实现类User
			*  public class User implements UserDetails,
			*  public User(String username, String password, Collection<? extends GrantedAuthority> authorities) {
			* */
			List<SimpleGrantedAuthority> authorities = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
			User user = new User(s, myUser.getUserpwd(), authorities);
			return user;
		}
		return null;
	}
}
